package com.surprise.es.service;

import java.util.List;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.Client;
import org.springframework.stereotype.Service;

/**
 * ESDeleteService.java
 * @author nick
 * 2015年3月10日
 */
@Service
public class ESDeleteService {    
    public void batchDeleteIds(Client client, String index, String type,
            List<Long> ids) throws ElasticsearchException {
        BulkRequestBuilder request = client.prepareBulk();
        for (Long id : ids) {
            request.add(client.prepareDelete(index, type, id + "")
                    .setOperationThreaded(false));
        }
        BulkResponse response = request.execute().actionGet();
        if (response.hasFailures()) {
            for (Long id : ids) {
                delete(client, index, type, id);
            }
        }
    }

    public String delete(Client client, String index, String type, Long id) {
        DeleteResponse response = client.prepareDelete(index, type, id + "")
                .setOperationThreaded(false)
                .execute()
                .actionGet();
        return response.getId();
    }
    
    public void batchDelete(Client client, String index, String type,
            List<String> ids) throws ElasticsearchException {
        BulkRequestBuilder request = client.prepareBulk();
        for (String id : ids) {
            request.add(client.prepareDelete(index, type, id)
                    .setOperationThreaded(false));
        }
        BulkResponse response = request.execute().actionGet();
        if (response.hasFailures()) {
            for (String id : ids) {
                delete(client, index, type, id);
            }
        }
    }

    public String delete(Client client, String index, String type, String id)
            throws ElasticsearchException {
        DeleteResponse response = client.prepareDelete(index, type, id)
                .setOperationThreaded(false)
                .execute()
                .actionGet();
        return response.getId();
    }
}
